package com.gome.extract;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.gome.extract.common.AppConfiguer;
import com.gome.extract.common.GlobalUtils;

  
public class MyThread extends GlobalUtils implements Runnable 
{  
	private static Logger logger = Logger.getLogger(MyThread.class);
	private HttpServletRequest mRequest;
    private AsyncContext asyncContext;   
    private boolean isEnd = false;
    
    public MyThread(AsyncContext asyncContext, HttpServletRequest request) 
	{  
        this.asyncContext = asyncContext;  
        mRequest = request;
    }  
    
    public boolean isEnd() {
    	return isEnd;
    }
    
	public synchronized void build()
	{
		String dbName = mRequest.getParameter("db");
		String collectName = mRequest.getParameter("rc_name");
		String useHBaseTransitString = mRequest.getParameter("use_hbase");
		boolean useHBaseTransit = false;
		if (useHBaseTransitString != null)
			useHBaseTransit = useHBaseTransitString.equals("1") ? true : false;
		
		logger.info(dbName + "\t" + collectName);
		if(dbName==null || collectName==null)
		{
			try
			{
				PrintWriter out = asyncContext.getResponse().getWriter();
				out.print("2");
	    		out.flush();  
	    		asyncContext.complete();
			}
			catch(Exception e)
			{
				asyncContext.complete();
			}
			return;
		}
		try
		{
			logger.info("return 2");
			PrintWriter out  = asyncContext.getResponse().getWriter(); 
			out.print("1");
    		out.flush();  
    		out.close();
    		asyncContext.complete();
		    return;
		}
		catch(Exception e)
		{
			
		}
		finally
		{
			DBOperator db = new DBOperator();
			if(db.build(dbName, collectName, useHBaseTransit)==false)
			{

			}
		}
	}
	
	public void select()
	{		
		String rcname = mRequest.getParameter("rc_name");
		String stepID = mRequest.getParameter("step_id");
		String icname = mRequest.getParameter("ic_name");
		
		if(rcname==null || rcname=="null")
		{
			try
			{
				PrintWriter out = asyncContext.getResponse().getWriter();
				out.print("2");
	    		out.flush();  
				asyncContext.complete();
			}
			catch(Exception e)
			{
				asyncContext.complete();
			}
			return;
		}
		
		try
		{
			
			PrintWriter out = asyncContext.getResponse().getWriter();
			out.print("1");
    		out.flush();  
//    		out.close();
    		asyncContext.complete();
		    return;
		}
		catch(Exception e)
		{
			asyncContext.complete();
		}
		finally
		{
			long startInit = System.currentTimeMillis();
			String dictName = AppConfiguer.getStringByKey("mid_datapath") + "/" + rcname + ".dic";
			String dataName = AppConfiguer.getStringByKey("mid_datapath") + "/" + rcname + ".dat";
			FileReader fr = new FileReader(dictName, dataName);
			fr.run(stepID, rcname, icname);
			
			long endInit = System.currentTimeMillis();				
	 	   	long chaInit = endInit - startInit;
			logger.info("共耗时:" + chaInit/1000 + "秒");
		}
	}
	
	public void test()
	{
		String urlString = mRequest.getParameter("url");
		if(urlString==null)
		{
			try
			{
				PrintWriter out = asyncContext.getResponse().getWriter();
				out.print("2");
	    		out.flush();  
				asyncContext.complete();
				return;
			}
			catch(Exception e)
			{
				asyncContext.complete();
				return;
			}
		}
		
		try
		{
			String name = mRequest.getParameter("rc_name");
			String stepID = mRequest.getParameter("step_id");
			  
			TestURL tt = new TestURL(urlString);
			String page = tt.getURL();
			HTMLScanner mScan = new HTMLScanner();
			HashMap<String, Vector<String>> mapResult = mScan.test(page);
			String dbName = AppConfiguer.getStringByKey("read_db");
			String confCollectName = AppConfiguer.getStringByKey("conf_collect");
			DBOperator db = new DBOperator();
			Vector<String> vec = db.read(dbName, confCollectName, stepID, name);
			String result = "";
			for(int i=0; i<vec.size(); ++i)
			{
				String k = vec.elementAt(i).split(TAB)[1];
				result +=  vec.elementAt(i).split(TAB)[0] + ":\t";
				if(mapResult.containsKey(k))
				{	
					Vector<String> v = mapResult.get(k);
					String s = v.elementAt(0);

					for(int j=1; j<v.size(); ++j)
					{
						if(v.elementAt(0).length()>10)
							s += "<br>" + v.elementAt(j);
						else
							s += "##" + v.elementAt(j);
					}	
					result += s + "<br>";
				}
			}
			
			PrintWriter out =  asyncContext.getResponse().getWriter();
			out.print(result);
			asyncContext.complete();
		}
		catch(Exception e)
		{
			asyncContext.complete();
			logger.error(AppConfiguer.getTrace(e));
		}
		
	}
	
    public void run() 
	{
		String requestType = mRequest.getParameter("type");	
		String dbName = mRequest.getParameter("db");
		String collectName = mRequest.getParameter("rc_name");
		logger.info("run " + dbName + "." + collectName + " : " + requestType);
		if(requestType==null)
		{
			asyncContext.complete();
			return;
		}
		if(requestType.equals("build"))
		{
			logger.info("run build " + dbName + "." + collectName);
			build();
		}
		else if(requestType.equals("select"))
		{
			logger.info("run select " + dbName + "." + collectName);
			select();
		}
		else if(requestType.equals("test"))
		{
			logger.info("run test " + dbName + "." + collectName);
			test();
		}
		else
		{
			isEnd = true;
			return;
		}
		isEnd = true;
	}
}  